package com.cqjtu.store.aop;

import com.cqjtu.store.common.Constants;
import com.cqjtu.store.common.JwtUtils;
import com.cqjtu.store.system.mapper.ViewCntMapper;
import com.cqjtu.store.system.pojo.entity.ViewCnt;
import com.cqjtu.store.user.pojo.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ProjectName: cqjtu-store
 * @Titile: UserOptAspect
 * @Author: Lucky
 * @Description: 收集用户行为的切面
 */
@Component //组件
@Aspect //切面
@Slf4j
public class UserOptAspect {
    @Autowired
    ViewCntMapper viewCntMapper;
    //表达式：去扫描指定的包以及类的方法
    @Around("execution(* com.cqjtu.store.product.service.impl.*.*(..))")
    public Object getOptAdvice(ProceedingJoinPoint jp) throws Throwable {
        //获取方法名
        String methodName = jp.getSignature().getName();
        //获取参数列表
        Object[] args = jp.getArgs();
        //商品编号
        Integer productId = -1;
        //获取用户
        UserLoginVO user = getUser();
        if (user == null) {
            return jp.proceed();
        }
        switch (methodName) {
            case "getById": //查看商品
                // 获取用户的编号 以及商品编号 ……
                productId = (Integer) args[0];
                ViewCnt viewCnt = new ViewCnt();
                viewCnt.setProductId(productId);
                viewCnt.setCategoryId(productId);
                viewCnt.setType(Constants.OPERATION_TYPE_PV);
                viewCnt.setUserId(user.getId());
                viewCntMapper.insert(viewCnt);
                break;
            case "???"://收藏？购买？购物车
                break;
            default:
                // todo
                break;
        }
        return jp.proceed();
    }

    /**
     * 获取当前用户的方法
     *
     * @return
     */
    private UserLoginVO getUser() {
        //在springmvc上下文去获取
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String token = request.getHeader("Authorization");

        if(token==null || token==""){
            return null;
        }
        UserLoginVO userLoginVO = JwtUtils.parseToken(token);
        return userLoginVO;
    }
}
